
import json

from django import http
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from utils.cookiesecret import CookieSecret
from utils.response_code import RETCODE

#购物车的简单展示
class CartsSimpleView(View):
    def get(self,request):
        #判断登陆
        if request.user.is_authenticated:
                # 登陆  reids
            redis_client = get_redis_connection('carts')
            cart_data = redis_client.hgetall(request.user.id)
                #字典推到式
            cart_dict = {int(key.decode()):json.loads(value.decode())for key,value in cart_data.items()}

        else:
            # 未登录  cookie
            cookie_str = request.COOKIES.get("carts")
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}
        # 构建数据的格式
        skus = SKU.objects.filter(id__in = cart_dict.keys())
        skus_list = []
        for sku in skus:
            skus_list.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })
        # 响应json列表数据
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_skus': skus_list})


#全选购物车
class CartsAllSelectedView(View):
    def put(self,request):
        #接受参数
        selected = json.loads(request.body.decode()).get('selected',True)
        if selected:
            if not isinstance(selected,bool):
                return http.HttpResponseForbidden("selected 不是bool类型")

        #判断用户是否登陆
        user= request.user
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        if user.is_authenticated:
            carts_redis_client = get_redis_connection('carts')
            carts_data = carts_redis_client.hgetall(user.id)
        # 登陆 redis
            #遍历所有商品
            for key,value in carts_data.items():
                sku_id =int(key.decode())
                carts_dict = json.loads(value.decode())
                carts_dict['selected'] = selected
                carts_redis_client.hset(user.id,sku_id,json.dumps(carts_dict))
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        else:
            #取出cookie值
            carts_str = request.COOKIES.get("carts")
            #判断cookie里面是否有值
            if carts_str:
                carts_dict =CookieSecret.loads(carts_str)
                for sku_id in carts_dict:
                    carts_dict[sku_id]['selected'] = selected
                dumps_carts_str = CookieSecret.dumps(carts_dict)
                response.set_cookie('carts',dumps_carts_str,max_age = 14*24*3600)
        return response


        #未登录 cookie

#购物车的增删改查
class CartsView(View):
    def post(self,request):
        #接收非form --json参数
        #json.loads将string转化为dict类型
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected',True)
        #校验 商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)#得到商品信息
        except Exception as e:
            return http.HttpResponseForbidden("商品不存在")
        try:  #判断count的类型
            count = int(count)
        except:
            return http.HttpResponseForbidden("count类型不对")
        if selected:
            if not isinstance(selected,bool):
                return http.HttpResponseForbidden("selected 类型不对")

        #判断登陆
        user = request.user
        response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
        if user.is_authenticated:
        # 登陆状态给redis
            redis_carts_client = get_redis_connection('carts')
            #连接redis
            client_data = redis_carts_client.hgetall(user.id)
            #查询该用户的所有购物信息
            if str(sku_id).encode() in client_data:  #sku_id先转化为字符串再转化为字节
                bytes_carts = client_data[str(sku_id).encode()]
                str_carts = bytes_carts.decode() #二进制转字符串
                dict_carts = json.loads(str_carts) #字符串转字典

                # count存在就累加
                dict_carts['count'] +=count

                #重新 覆盖 原来的
                redis_carts_client.hset(user.id,sku_id,json.dumps(dict_carts))
            else:
                redis_carts_client.hset(user.id,sku_id,json.dumps({"count": count, "selected": selected}))
            #判断是否存在count和selected的状态
            #重新覆盖以前的数据信息
        else:
            # 未登录状态 给cookie
            cookie_str =request.COOKIES.get('carts')
            #解密
            if cookie_str:
                carts_dict =CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}
            #判断 商品是否存在
            if sku_id in carts_dict:
                #存在  累加
                origi_count = carts_dict[sku_id]['count']
                count += origi_count
            #不存在 新增
                # 不存 新增
            carts_dict[sku_id] = {'count': count, 'selected': selected}

            # 3.2.4 加密--->str
            dumps_str = CookieSecret.dumps(carts_dict)

            # 重新插入cookie
            response.set_cookie('carts', dumps_str, max_age=14 * 24 * 3600)


                # 4.返回响应
        return response


        # 返回给前端结果
    def get(self,request):
        #判断是否登陆
        user = request.user
        if user.is_authenticated:
            #登陆  获取数据 -redis
            client = get_redis_connection('carts')
            carts_redis = client.hgetall(user.id)  #取出来的是字节
            # print(type(carts_redis),carts_redis)
#<class 'dict'> {b'8': b'{"selected": true, "count": 1}', b'1': b'{"selected": true, "count": 1}', b'10': b'{"selected": true, "count": 1}'}
            carts_dict = {}
            for key,value in carts_redis.items():
                cart_key = int(key.decode())  #loads字符串转字典
                cart_redis_dict = json.loads(value.decode())
                carts_dict[cart_key] = cart_redis_dict
        else:#没有登陆  获取cookie缓存的数据
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}
        #从购物车数据 获取 所有sku_ids
        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),
                'count': carts_dict[sku.id]['count'],
                'selected': str(carts_dict[sku.id]['selected']),
                'amount': str(sku.price * carts_dict[sku.id]['count']),

            })

        context = {
            'cart_skus': cart_skus
        }
        # print(cart_skus)

        return render(request, 'cart.html', context)
    def put(self,request):

        #修改购物车
        #接收和检验参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected',True)

        #检验
        try:
            sku = SKU.objects.get(id= sku_id)
        except:
            return http.HttpResponseForbidden("商品信息不存在")
        try:
            count = int(count)
        except:
            return http.HttpResponseForbidden("count类型不对")
        if selected:
            if not isinstance(selected,bool):
                return http.HttpResponseForbidden("selected 不是bool类型数据")
        #判断用户是否登陆
        cookie_cart_str = ''
        if request.user.is_authenticated:
            cart_redis_client = get_redis_connection('carts')
            #直接接收前端的数据  然后进行覆盖
            data = {'count':count,'selected':selected}  #直接采用覆盖的方式
            cart_redis_client.hset(request.user.id,sku_id,json.dumps(data))
        #登陆状态,使用redis修改
        else:
        #未登录状态  使用cookie进行修改
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
            #直接覆盖以前的数据信息
            cart_dict[sku_id] = {'count':count,'selected':selected}
            cookie_cart_str = CookieSecret.dumps(cart_dict) #转化为密文数据信息
        # 构建前端的数据
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }
        response = JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        if not request.user.is_authenticated:
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
        return response
    def delete(self,request):
        # 接收和检验参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        # 检验
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return http.HttpResponseForbidden("商品信息不存在")
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            carts_redis_client = get_redis_connection('carts')
            #根据用户id删除商品sku
            carts_redis_client.hdel(user.id,sku_id)
            # 删除结束后，没有响应的数据，只需要响应状态码即可
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
        else:
            # 用户未登录，删除cookie购物车
            cart_str = request.COOKIES.get('carts')  #查询
            if cart_str:
                # 转成明文   得到字典类型数据
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            # 创建响应对象
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                # 删除数据
                del cart_dict[sku_id]
                # 将字典转成密文
                cookie_cart_str = CookieSecret.dumps(cart_dict)
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str, max_age=24 * 30 * 3600)
            return response